package com.slaoren.mvvmexamp.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import java.lang.reflect.ParameterizedType

abstract class BaseFragment<T : ViewDataBinding, M: ViewModel>:Fragment() {
    lateinit var mBinding:T
    var mViewModel:M ?=null

    abstract fun getLayoutId():Int

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        mBinding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false)
        mBinding.lifecycleOwner = this
        setVM()
        setView()
        return mBinding.root
    }

    abstract fun setView()

    private fun setVM(){
        val type = this.javaClass.genericSuperclass //获取泛型
        if (type is ParameterizedType) {
            val targetType = type.actualTypeArguments[1]//获取第二个参数
            if (targetType is Class<*>) {
                mViewModel = ViewModelProvider(requireActivity()).get(targetType as Class<M>)
            }
        }
    }
}